package com.lsy.wallet.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lsy.wallet.mapper.UserWalletMapper;
import com.lsy.wallet.pojo.UserWallet;
import com.lsy.wallet.service.api.UserWalletService;
import com.lsy.wallet.vo.ConsumptionVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

/**
 * @author lsyandwh
 * @create 2023-03-07 16:58
 */
@Service
public class UserWalletServiceImpl implements UserWalletService {

    @Autowired
    private UserWalletMapper userWalletMapper;

    @Override
    public UserWallet getWalletDetailByUserId(Long userId) {

        QueryWrapper<UserWallet> wrapper = new QueryWrapper<>();
        wrapper.eq(userId != null,"user_id",userId);
        UserWallet userWallet = userWalletMapper.selectOne(wrapper);

        if(userWallet == null) throw new RuntimeException("请求不合法");

        return userWallet;
    }

    /**
     * 修改用户可用余额与冻结金额
     * @param consumptionVo
     */
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    @Override
    public void addAndSubtractBalance(ConsumptionVo consumptionVo) {

        BigDecimal money = consumptionVo.getMoney();

        Long rollOutWalletId = consumptionVo.getRollOutWalletId();
        UserWallet rollOutUserWallet = userWalletMapper.selectById(rollOutWalletId);

        if(null == rollOutUserWallet) throw new RuntimeException("请求不合法");

        rollOutUserWallet.setAvailableBalance(rollOutUserWallet.getAvailableBalance().subtract(money));//可用余额递减

        //TODO 也可将冻结金额存入第三方账户，用户收货时再将金额打给商户
        rollOutUserWallet.setFreezeBalance(rollOutUserWallet.getFreezeBalance().add(money));//冻结余额递增

        userWalletMapper.updateById(rollOutUserWallet);
    }

    /**
     * 退款，修改账户余额
     * @param rollOutWalletId
     * @param refundMoney
     */
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    @Override
    public void refund(Long rollOutWalletId, BigDecimal refundMoney) {
        UserWallet userWallet = userWalletMapper.selectById(rollOutWalletId);

        userWallet.setFreezeBalance(userWallet.getFreezeBalance().subtract(refundMoney));
        userWallet.setAvailableBalance(userWallet.getAvailableBalance().add(refundMoney));

        userWalletMapper.updateById(userWallet);
    }
}
